package com.hjw.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.hjw.config.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AlipayService {
    private final AlipayConfig config;

    public AlipayService(AlipayConfig config) {
        this.config = config;
    }

    private String cleanPrivateKey(String privateKey) {
        // 先将所有换行符统一为 \n
        privateKey = privateKey.replaceAll("\\r\\n|\\r", "\n");
        // 再去除所有空白字符
        return privateKey.replaceAll("\\s+", "");
    }

    public String createPayRequest(String orderNo, String subject, String totalAmount) throws AlipayApiException {
        log.info("使用的网关URL: {}", config.getGatewayUrl()); // 添加这行
        if (orderNo == null || orderNo.isEmpty()) {
            throw new IllegalArgumentException("订单号不能为空");
        }
        AlipayClient client = new DefaultAlipayClient(
                "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
                config.getAppId(),
                cleanPrivateKey(config.getMerchantPrivateKey()),
                "json",
                "UTF-8",
                config.getAlipayPublicKey(),
                "RSA2"
        );

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(config.getReturnUrl());
        request.setNotifyUrl(config.getNotifyUrl());

        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(orderNo);
        model.setSubject(subject);
        model.setTotalAmount(totalAmount);
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        request.setBizModel(model);

        // 获取支付宝响应并返回原始表单
        AlipayTradePagePayResponse response = client.pageExecute(request);

        return response.getBody();
    }
}